<?php

namespace app\user\controller;
use app\index\common\JwtAuth;
use app\index\common\ApiResponse;
use app\index\controller\Base;
use app\index\model\Order;

class Index extends Base
{
    public function index(){
        $params = request()->param();
        $jwtAuth = new JwtAuth();
        $payload = $jwtAuth->getPayload($params['token']);
        if($payload['level'] > 2){
            return ApiResponse::json(300,'您还不是管理员',null);
        }
        $page = input('page');
        $pageSize = input('pageSize');
        $userName = input('userName');
        $user = model('User');
        $where = [];
        if (!empty($userName)) {
            // 如果dishName不为空，则进行模糊匹配
            $where[] = ['userName','like', '%' . $userName . '%'];
        }
        $users = $user->where($where)->paginate($pageSize, false, ['page' => $page]);
        return ApiResponse::json(200,'success',$users);
    }
    public function userInfo(){
        $token = input('token');
        if (empty($token)) {
            return ApiResponse::json(300,'未登录',null);
        }
        $jwtAuth = new JwtAuth();
        $payload = $jwtAuth->getPayload($token);
        $uid = $payload['userId'];
        $userModel = model('User');
        $targetUser = $userModel::get(['id' => $uid]);
        return ApiResponse::json(200,'success',$targetUser);
    }
    public function deleteUser(){
        $params = request()->param();
        $jwtAuth = new JwtAuth();
        $payload = $jwtAuth->getPayload($params['token']);
        if($payload['level'] > 2){
            return ApiResponse::json(300,'您还不是管理员',null);
        }
        $uid = $params['userId'];//要修改的用户的id
        $userModel = model('User');
        $targetUser = $userModel::get(['id' => $uid]);
        if(empty($targetUser)){
            return ApiResponse::json(300,'目标用户不存在',null);
        }
        $targetUser->delete();
        return ApiResponse::json(200,'success',null);
    }
    public function changeLevel(){
        $uid = input('id');//要修改的用户的id
//        $jwtAuth = new JwtAuth();
//        $payload = $jwtAuth->getPayload($params['token']);
        $userModel = model('User');
        $targetUser = $userModel::get(['id' => $uid]);
        if(empty($targetUser)){
            return ApiResponse::json(300,'目标用户不存在',$uid);
        }
        $targetUser->level = input('level');
        $targetUser->save();
        return ApiResponse::json(200,'success',null);
    }
    public function changeUserType(){
        $params = request()->param();
        $uid = $params['userId'];//要修改的用户的id
        $type = $params['type'];
        if(empty($type)){
            return ApiResponse::json(300,'用户状态不正确',null);
        }
//        $jwtAuth = new JwtAuth();
//        $payload = $jwtAuth->getPayload($params['token']);
        $userModel = model('User');
        $targetUser = $userModel::get(['id' => $uid]);
        if(empty($targetUser)){
            return ApiResponse::json(300,'目标用户不存在',null);
        }
        $targetUser->type = $params['type'];
        $targetUser->save();
        return ApiResponse::json(200,'success',null);
    }
    public function changeScore(){
        $params = request()->param();
        $uid = $params['userId'];//要修改的用户的id
        $score = $params['score'];
        $type = $params['type'];

        $jwtAuth = new JwtAuth();
        $payload = $jwtAuth->getPayload($params['token']);
        if($payload['level'] > 2){
            return ApiResponse::json(300,'您还不是管理员',null);
        }

        if(empty($score)){
            return ApiResponse::json(300,'金额必须大于0',null);
        }
        $userModel = model('User');
        $targetUser = $userModel::get(['id' => $uid]);
        if(empty($targetUser)){
            return ApiResponse::json(300,'目标用户不存在',null);
        }
        //1增加积分 2扣减积分
        if ($type===1){
            $amount = $targetUser->score + $params['score'];
        }else{
            $amount = $targetUser->score - floatval($params['score']);
        }
        $targetUser->score = $amount;
        $targetUser->save();
        $orderId = input('orderId');
        $orderModel = model('Order');
        if(!empty($orderId)){
            $userOrderModel = model('UserOrder');
            $targetOrder = $userOrderModel::get(['id' => $orderId]);
            $targetOrder->score = $params['score'];
            $targetOrder->save();
        }
        $orderModel->save([
            'userName' => $targetUser->userName,
            'userId' => $targetUser->id,
            'actionUserName' => $payload['userName'],
            'actionUserId' => $payload['userId'],
            'type' => $type,
            'refer' => $params['refer'],
            'score' => $params['score'],
            'scoreAfter'=>$amount
        ]);

        return ApiResponse::json(200,'success',null);
    }
    public function scoreList(){
        $token = input('token');
        $userName = input('userName'); // 获取dishName参数
        $dateList = input('dateList/a'); // 获取dateList参数（转为数组）

        $jwtAuth = new JwtAuth();
        $payload = $jwtAuth->getPayload($token);

        $orderModel= model('Order');
        $where = [];
        if($payload['level'] > 2){
            $selfName = $payload['userName'];
            $where[] = ['userName','like', '%' . $selfName . '%'];
        }else{
            if (!empty($userName)) {
                // 如果dishName不为空，则进行模糊匹配
                $where[] = ['userName','like', '%' . $userName . '%'];
            }
        }

        if(!$dateList){
            return ApiResponse::json(200,'succeed','查询日期不能为空');
        }
        //查询近30天所有userOrder，过滤已截止时间
        $this->configOrderToConsume($payload);

        $startDate = strtotime($dateList[0] . ' 00:00:00');
        $endDate = strtotime($dateList[1] . ' 23:59:59');

        $page = input('page');
        $pageSize = input('pageSize');
        $list = $orderModel->where($where)
            ->whereTime('create_time','between', [$startDate,$endDate])
            ->order('create_time', 'desc') // 按create_time字段倒序排序
            ->paginate($pageSize, false, ['page' => $page]);
        return ApiResponse::json(200,'succeed',$list);
    }
    public function configOrderToConsume($payload){
        $userOrderModel = model('UserOrder');
        $gearModel = model('Gears');
        $gears = $gearModel::all();
        $gearMap = [];
        foreach ($gears as $gear) {
            $gearMap[$gear->value] = $gear;
        }

        $now = time();
        $thirtyDaysAgo = strtotime('-30 days');
        $userOrderList = $userOrderModel->where('create_time', '>=', $thirtyDaysAgo)
            ->where('create_time', '<=', $now)
            ->where(function($query) {
                $query->where('orderType', '=', 0)
                    ->whereOr('orderType', 'null');
            })->select();
        $expiredFoods = [];
        $nowFormatted = date('Y-m-d H:i:s', $now);
        foreach ($userOrderList as $userOrder){
            $gear = $gearMap[$userOrder->timeRange];
            $finalTime = $userOrder->targetDate . ' ' . $gear->ableEndTime . ':00';

            // 判断当前时间是否超过 targetDateTime
            if (strtotime($nowFormatted) > strtotime($finalTime)) {
                // 将菜品对象存入 expiredFoods 数组
                $expiredFoods[] = $userOrder;
            }
        }
        $curThirtyDayOrders = model('Order')->where('create_time','>=',$thirtyDaysAgo)
            ->where('dishId', 'neq', '')
            ->where('dishId', 'not null')
            ->select();
        foreach ($expiredFoods as $order){
            $foundOrder = null;
            foreach ($curThirtyDayOrders as $mo) {
                if ($mo['dishId'] === $order['dishId']) {
                    $foundOrder = $mo;
                    break;
                }
            }
            if ($foundOrder) {
                // 存在匹配的数据
                continue;
            }else{
                $orderModel = new Order();
                $data = [
                    'userName' => $order->userName,
                    'userId' => $order->userId,
                    'actionUserName' => '',
                    'actionUserId' => '',
                    'type' => 2,
                    'dishId' => $order->dishId,
                    'orderType' => 0,
                    'refer' => 'preOrder',
                    'score' => 0,
                    'scoreAfter' => 0
                ];
                $orderModel->save($data);
            }
        }
    }
    public function exportUserScore(){
        $targetUser = input('userName');
        $token = input('token');
        $dateList = input('dateList/a'); // 获取dateList参数（转为数组）
        $jwtAuth = new JwtAuth();
        $payload = $jwtAuth->getPayload($token);
        $userName = $payload['userName'];
//        if ($userName != $targetUser && $payload['level'] > 2) {
//            return ApiResponse::json(300,'您还不是管理员，不能查询除自己外的他人数据',null);
//        }
        $where = [];
        if($payload['level'] > 2){
            $where[] = ['userName','like', '%' . $userName . '%'];
        }else{
            if (!empty($targetUser)) {
                // 如果dishName不为空，则进行模糊匹配
                $where[] = ['userName','like', '%' . $targetUser . '%'];
            }
        }

        $startDate = strtotime($dateList[0] . ' 00:00:00');
        $endDate = strtotime($dateList[1] . ' 23:59:59');
        $orderModel= model('Order');
//        var_dump($dateList);
        $list = $orderModel->where($where)
            ->whereTime('create_time','between', [$startDate,$endDate])
            ->order('create_time', 'desc')->select();
        return ApiResponse::json(200,'succeed',$list);
    }
    public function exportUsers(){
        $token = input('token');

        $jwtAuth = new JwtAuth();
        $payload = $jwtAuth->getPayload($token);
        if($payload['level'] > 2){
            return ApiResponse::json(300,'您还不是管理员',null);
        }
        $user = model('User');
        $re = $user->field(['id', 'userName', 'score'])->select();
        return ApiResponse::json(200,'succeed',$re);
    }
    public function importUsers() {
        $token = input('token');
        $userList = input('userList/a'); // 获取 userList 参数（转为数组）

        $jwtAuth = new JwtAuth();
        $payload = $jwtAuth->getPayload($token);
        if ($payload['level'] > 2) {
            return ApiResponse::json(300, '您还不是管理员', null);
        }

        $userModel = model('User');
        $existArr = [];
        $userNames = array_column($userList, 'userName');

        // 批量查询现有用户
        $existingUsers = $userModel->whereIn('userName', $userNames)->select();
        $existingUsersMap = [];
        foreach ($existingUsers as $user) {
            $existingUsersMap[$user->userName] = $user;
        }

        foreach ($userList as &$user) {
            if (isset($existingUsersMap[$user['userName']])) {
                $mo = $existingUsersMap[$user['userName']];
                $mo->score = floatval($mo->score) + floatval($user['score']);
                $mo->save();
                $existArr[] = $user; // 使用短数组语法
            } else {
                $user['password'] = '123456';
                $user['level'] = 3;
                $user['type'] = 1;
            }
        }

        // 筛选出需要插入的新用户
        $filteredA = array_filter($userList, function($item) use ($existArr) {
            return !in_array($item['userName'], array_column($existArr, 'userName'));
        });

        try {
            $userModel->saveAll($filteredA);
        } catch (\Exception $e) {
            return ApiResponse::json(300, $e->getMessage(), null);
        }

        return ApiResponse::json(200, 'succeed', null);
    }

    public function modifyUserPsw(){
        $token = input('token');
        $psw = input('psw');
        $jwtAuth = new JwtAuth();
        $payload = $jwtAuth->getPayload($token);
        $userModel = model('User')::get(['id' => $payload['userId']]);
        $userModel->save([
            'password' => $psw,
        ]);
        return ApiResponse::json(200,'succeed',null);
    }
}